package com.dotstone.chipism.ui.timing;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.NumberPicker;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.dotstone.chipism.R;
import com.dotstone.chipism.activity.BaseActivity;
import com.dotstone.chipism.bean.Device;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.ui.timing.bean.TimingData;
import com.dotstone.chipism.ui.timing.util.AddSocketTimingManager;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.SPUtils;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class AddSocketTimingActivity extends BaseActivity {

    public static final int ADD_SUCCESS_REQUEST_CODE = 0x01;
    public static final int ADD_SUCCESS_RESULT_CODE = 0x02;

    private TextView tvTitle;
    private TextView mStatusBar;
    private Button btnAdd;
    private View btnBack;
    private NumberPicker npHour , npMIn;//时间跟分钟的选择器
    private RadioGroup rg_switch;
    private Device device;
    private SVProgressHUD mSVProgressHUD;

    private CheckBox cbWeek_1;
    private CheckBox cbWeek_2;
    private CheckBox cbWeek_3;
    private CheckBox cbWeek_4;
    private CheckBox cbWeek_5;
    private CheckBox cbWeek_6;
    private CheckBox cbWeek_7;

    List<CheckBox> cbWeeks;


    private ToggleButton onoff_model;//重复模式

    private boolean isUpdate ; //是否是编辑状态

    @Override
    public void widgetClick(View v) {
        switch (v.getId()){
            case R.id.back_layout:
                finish();
                break;
            //保存
            case R.id.nextstep:
                mSVProgressHUD.showWithStatus("正在保存中...");

                String taskName = "";

                JSONObject obj = new JSONObject();
                try {

                    if (rg_switch.getCheckedRadioButtonId() == R.id.rb_switch_open){
                        taskName = "开";
                        JSONObject jo = new JSONObject();
                        jo.put("cmd", 101);
                        if (device.getDataOpenCmd() != null && device.getDataOpenCmd().length != 0) {
                            JSONArray ja = new JSONArray();
                            for (int i = 0; i < device.getDataOpenCmd().length; i++) { // 依次将数组元素添加进JSONArray对象中
                                ja.put(device.getDataOpenCmd()[i]);
                            }
                            jo.put("data", ja);
                        }

                        obj.put("body", jo.toString());
                    } else {
                        taskName = "关";
                        JSONObject jo = new JSONObject();
                        jo.put("cmd", 101);
                        if (device.getDataCloseCmd() != null && device.getDataCloseCmd().length != 0) {
                            JSONArray ja = new JSONArray();
                            for (int i = 0; i < device.getDataCloseCmd().length; i++) { // 依次将数组元素添加进JSONArray对象中
                                ja.put(device.getDataCloseCmd()[i]);
                            }
                            jo.put("data", ja);
                        }
                        obj.put("body", jo.toString());
                    }
                    obj.put("hid", DeviceManager.getInstance().hid);

                    if (onoff_model.isChecked()){
                        obj.put("cycle", true);//是否重复
                    }else {
                        obj.put("cycle", false);//是否重复
                    }

                    //判断是否有选择
                    boolean isSelected = false;
                    StringBuffer sb = new StringBuffer("0");

                    for (int i = 0 ; i < cbWeeks.size() ; i ++) {

                        sb.append(cbWeeks.get(i).isChecked() ? "1": "0");
                        if (cbWeeks.get(i).isChecked()){
                            isSelected = true;
                        }
                    }
                    //如果都没选中
                    if (!isSelected && !onoff_model.isChecked()) {

                        // 获取当前时间
                        Calendar calendar = Calendar.getInstance();
                        //小时
                        int hour = calendar.get(Calendar.HOUR_OF_DAY);
                        //分钟
                        int minute = calendar.get(Calendar.MINUTE);

                        boolean isInit = true;

                        //判断小时
                        if (npHour.getValue() < hour) {
                            isInit = false;
                            //小于当前时间，要进一天
                            int currentWeek = 0;
                            int weekDay = new Date().getDay();
                            if (weekDay == 0) {
                                weekDay = 7;
                            }
                            currentWeek = weekDay + 1;
                            if (currentWeek == 8) {
                                currentWeek = 1;
                            }

                            sb.replace(7 -currentWeek + 1 , 7 -currentWeek + 1+ 1  , "1");

                        } else if (npHour.getValue() == hour) {
                            //判断分钟
                            if (npMIn.getValue() <= minute) {
                                isInit = false;
                                //小于当前时间，要进一天
                                int currentWeek = 0;
                                int weekDay = new Date().getDay();
                                if (weekDay == 0) {
                                    weekDay = 7;
                                }
                                currentWeek = weekDay + 1;
                                if (currentWeek == 8) {
                                    currentWeek = 1;
                                }
                                sb.replace(7 - currentWeek+ 1  , 7 -currentWeek + 1+ 1  , "1");
                            }
                        }
                        if (isInit) {

                            //小于当前时间，要进一天
                            int currentWeek = 0;
                            int weekDay = new Date().getDay();
                            if (weekDay == 0) {
                                weekDay = 7;
                            }
                            currentWeek = weekDay;
                            if (currentWeek == 8) {
                                currentWeek = 1;
                            }

                            sb.replace(7 - currentWeek + 1 , 7 -currentWeek + 1 + 1 , "1");
                        }
                    }

                    if (!isSelected && onoff_model.isChecked()) {
                        sb = new StringBuffer("01111111");
                    }

                    Log.i("push_week" , "push_week:" + sb.toString());

                    obj.put("push_week", bitToByte(sb.toString()));
                    String min = npMIn.getValue() < 10 ? "0" + npMIn.getValue() :""+ npMIn.getValue();
                    obj.put("pushTime", npHour.getValue() + ":" + min);
                    int sendNumber = 0;
                    for (int i = 0 ; i < sb.toString().length() ; i ++) {
                        if (sb.charAt(i) == '1'){
                            sendNumber ++;
                        }
                    }

                    obj.put("sendNumber", sendNumber);//发送次数
                    obj.put("deviceId", device.getMainDeviceId());
                    obj.put("key", "10000");
                    obj.put("requestTime", "" + System.currentTimeMillis());
                    obj.put("taskName", taskName);
                    obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
                } catch (JSONException e1) {
                    e1.printStackTrace();
                }

//                AddTimingBean a = new AddTimingBean(device.getOpenCmd());

                Log.i("onResponse" , "content:" + obj.toString());


                //获取定时数据
                OkHttpUtils.postString().url(HttpURL.SAVE_TIMING)
                        .mediaType(MediaType.parse("application/json;charset=UTF-8"))
                        .content(obj.toString())
                        .build().readTimeOut(5000)
                        .writeTimeOut(5000).connTimeOut(5000)
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Request request, Exception e) {
                                showToast("添加定时失败");
                                mSVProgressHUD.dismiss();
                            }

                            @Override
                            public void onResponse(String response) {
                                mSVProgressHUD.dismiss();
                                Log.i("onResponse" , "onResponse:" + response);
                                try {
                                    JSONObject jsonObject = new JSONObject(response);
                                    String value = jsonObject.getString("resultCode");
                                    if (value.equals("1")){
                                        showToast("添加成功");
                                        setResult(ADD_SUCCESS_RESULT_CODE);
                                        finish();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });

                break;
        }
    }
//    06-28 20:29:12.835 4148-4148/com.dotstone.chipism I/sendCmd: cmd:{"a":"20000","b":0,"c":"20,247","d":"10,null","e":1,"f":1530188941841,"h":"0.0.1","g":"{\"cmd\":101,\"data\":[1,155,19,0,2,1,16,255,0,0]}"}
//06-28 20:29:13.355 4148-4148/com.dotstone.chipism I/sendCmd: cmd:{"a":"20000","b":0,"c":"20,247","d":"10,null","e":1,"f":1530188941842,"h":"0.0.1","g":"{\"cmd\":101,\"data\":[1,155,19,0,2,1,16,0,0,0]}"}

    public static int bytesToInt(byte[] src, int offset) {
        int value;
        value = (int) ((src[offset] & 0xFF)
                | ((src[offset+1] & 0xFF)<<8)
                | ((src[offset+2] & 0xFF)<<16)
                | ((src[offset+3] & 0xFF)<<24));
        return value;
    }

    @Override
    public void initParms(Bundle parms) {
        device = DeviceManager.getInstance().getDeviceById(AddSocketTimingManager.getInstance().getId());
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_add_socket_timing;
    }

    @Override
    public void initView(View view) {
        mStatusBar = $(R.id.tv_statusBar_mian);
        btnBack = $(R.id.back_layout);
        btnAdd = $(R.id.nextstep);
        tvTitle = $(R.id.title_tv);
        npHour = $(R.id.np_timing_h);
        npMIn = $(R.id.np_timing_m);
        rg_switch = $(R.id.rg_switch);

        cbWeek_1 = $(R.id.cbWeek_1);
        cbWeek_2 = $(R.id.cbWeek_2);
        cbWeek_3 = $(R.id.cbWeek_3);
        cbWeek_4 = $(R.id.cbWeek_4);
        cbWeek_5 = $(R.id.cbWeek_5);
        cbWeek_6 = $(R.id.cbWeek_6);
        cbWeek_7 = $(R.id.cbWeek_7);

        cbWeeks = new ArrayList<>();
        cbWeeks.add(cbWeek_7);
        cbWeeks.add(cbWeek_6);
        cbWeeks.add(cbWeek_5);
        cbWeeks.add(cbWeek_4);
        cbWeeks.add(cbWeek_3);
        cbWeeks.add(cbWeek_2);
        cbWeeks.add(cbWeek_1);

        onoff_model = $(R.id.onoff_model);


        rg_switch.check(R.id.rb_switch_close);

        mSVProgressHUD = new SVProgressHUD(this);
    }

    @Override
    public void setListener() {
        tvTitle.setText("添加定时");
        btnAdd.setText("保存");
        btnAdd.setVisibility(View.VISIBLE);
        mStatusBar.setVisibility(View.VISIBLE);
        btnBack.setOnClickListener(this);
        btnAdd.setOnClickListener(this);
        npHour.setMinValue(0);
        npHour.setMaxValue(23);

        npHour.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);

        npMIn.setMinValue(0);
        npMIn.setMaxValue(60);

        npMIn.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);

        rg_switch.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (radioGroup.getCheckedRadioButtonId()){
                    case R.id.rb_switch_open:
                        break;
                    case R.id.rb_switch_close:
                        break;
                }
            }
        });



    }

    @Override
    public void doBusiness(Context mContext) {
        TimingData timingData = (TimingData) getIntent().getSerializableExtra("timingData");
        if (timingData != null) {
            //设置为编辑状态
            isUpdate = true;
            String[] pushTimes = timingData.getPushTime().split(":");
            //设置时间
            if (pushTimes.length > 1) {
                npHour.setValue(Integer.parseInt(pushTimes[0]));
                npMIn.setValue(Integer.parseInt(pushTimes[1]));
            }
            //设置是否重复模式
            onoff_model.setChecked(timingData.isCycle() ? true : false);
            rg_switch.check(timingData.getTaskName().equals("开") ? R.id.rb_switch_open :R.id.rb_switch_close);

            Log.i("星期" , "星期111111111111:" + timingData.getPush_week());
            String pushWeeks = getBit((byte) timingData.getPush_week());

            Log.i("星期" , "星期22222222222:" + pushWeeks);

            cbWeek_1.setChecked(pushWeeks.charAt(7) == '1' ? true : false);
            cbWeek_2.setChecked(pushWeeks.charAt(6) == '1' ? true : false);
            cbWeek_3.setChecked(pushWeeks.charAt(5) == '1' ? true : false);
            cbWeek_4.setChecked(pushWeeks.charAt(4) == '1' ? true : false);
            cbWeek_5.setChecked(pushWeeks.charAt(3) == '1' ? true : false);
            cbWeek_6.setChecked(pushWeeks.charAt(2) == '1' ? true : false);
            cbWeek_7.setChecked(pushWeeks.charAt(1) == '1' ? true : false);
        } else {
            //获取当前时间
            Calendar calendar = Calendar.getInstance();
            //小时
            int hour = calendar.get(Calendar.HOUR_OF_DAY);

            npHour.setValue(hour);
            //分钟
            int minute = calendar.get(Calendar.MINUTE);

            npMIn.setValue(minute);
        }
    }


    public static int bitToByte(String bit) {
        int re, len;
        if (null == bit) {
            return 0;
        }
        len = bit.length();
        if (len != 4 && len != 8) {
            return 0;
        }
        if (len == 8) {// 8 bit处理
            if (bit.charAt(0) == '0') {// 正数
                re = Integer.parseInt(bit, 2);
            } else {// 负数
                re = Integer.parseInt(bit, 2) - 256;
            }
        } else {//4 bit处理
            re = Integer.parseInt(bit, 2);
        }
        return (byte) re;
    }


    public static String getBit(byte by){
        StringBuffer sb = new StringBuffer();
        sb.append((by>>7)&0x1)
                .append((by>>6)&0x1)
                .append((by>>5)&0x1)
                .append((by>>4)&0x1)
                .append((by>>3)&0x1)
                .append((by>>2)&0x1)
                .append((by>>1)&0x1)
                .append((by>>0)&0x1);
        return sb.toString();
    }


}
